import logging

from flask import Flask, request, session
from flask_cors import CORS
from flask_restful import Api, Resource
from database import Database




class Login(Resource):
    def __init__(self):
        self.logger = logging.getLogger(__name__)

    def post(self):
        db = Database()
        data = request.get_json()
        #TODO trim strings

        username = data.get('username')
        password = data.get('password')
        user_type = data.get('type')
        self.logger.info(username, password, user_type)

        user = None
        if user_type == 'user':
            user = db.execute_query("SELECT * FROM useraccount WHERE userId = %s ", (username,))[0]
        else:
            user = db.execute_query("SELECT * FROM manageraccount WHERE managerId = %s", (username,))[0]

        if user and user[1] == password:
            session['username'] = username
            session['type'] = user_type
            session.modified = True
            return {"message": "login successfully"}, 200
        else:
            return {"message": "Invalid username or password"}, 401
